package cc.wsyw126.java.Thread;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by junpeng.yang on 17/3/21.
 */
public class TestThreadLocal {

    public static void main(String[] args) {
        HashMap<Integer, Integer> a = new HashMap<>();
        a.put(1, 1);


        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadLocal<HashMap> local1 = new ThreadLocal<HashMap>() {
                    @Override
                    protected HashMap initialValue() {
                        return a;
                    }
                };
                HashMap<Integer, Integer> hashMap = local1.get();
                hashMap.put(2, 2);
                hashMap.put(4, 4);
                local1.set(hashMap);
                print(local1.get());

            }
        });

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadLocal<HashMap> local = new ThreadLocal<HashMap>() {
                    @Override
                    protected HashMap initialValue() {
                        return a;
                    }
                };
                HashMap<Integer, Integer> hashMap = local.get();
                hashMap.put(3, 3);
                local.set(hashMap);
                print(local.get());
            }
        });


        t.start();
        t1.start();

        ConcurrentMap<Integer, Integer> h = new ConcurrentHashMap<>();
        print(a);

    }

    static void print(HashMap<Integer, Integer> hashMap) {
        for (Map.Entry<Integer, Integer> integerIntegerEntry : hashMap.entrySet()) {
            System.out.println("integerIntegerEntry.getKey() = " + integerIntegerEntry.getKey());
            System.out.println("integerIntegerEntry.getValue() = " + integerIntegerEntry.getValue());
        }

        System.out.println();
    }
}
